<wxs src="../../wxcomponents/public/publicFun.wxs" module="publicFun"></wxs>
<template>
    <view class="material_library_detail_block" :style="'height: '+(showType=='imgArr'?screenHeight:'')+'px;position: '+(showType=='imgArr'?'absolute':'relitive')">
        <view class="material_library_detail_bg">
            <text class="material_library_detail_title">素材详情</text>
            <image @click="backPerPageFun()" :style="'top:'+ (1.5*statusBarHeightOne)+'px'" src="https://image1.sansancloud.com/linwenlaoshi/2020_9/18/14/13/34_54.jpg?x-oss-process=style/preview_120" class="back_page_icon"></image>
            <image  style="width: 100%;height: 167rpx;" src="https://image1.sansancloud.com/linwenlaoshi/2020_9/9/17/42/39_192.jpg"></image>
        </view>
        <view class="material_library_detail_container" :style="'height: '+(showType=='imgArr'?'100%':'')+';position: '+(showType=='imgArr'?'absolute':'relitive')+';margin-top: '+(showType=='imgArr'?'':'167rpx')">
            <view class="material_library_detail_type_list">
                <view class="material_library_detail_type_item" v-for="(item,index) in materialLibraryDetailTypeList" :key="index" @tap="bindTypeItem(index)" v-if="materialLibraryDetailTypeIndex==0?index<=1:index==2">
                    <text class="material_library_detail_type_item_text" :style="{borderBottom:selectTabIndex==index?('4rpx solid '+defaultColor):'',color:selectTabIndex==index?defaultColor:''}">{{item.name}}</text>
                </view>
            </view>
            <!-- <view> -->
            <view v-if="showType" :style="'height: '+(showType=='imgArr'?'100%':'')">
                <checkbox-group @change="checkboxChange" class="material_library_detail" v-if="showType=='img'">
                    <view class="material_library_detail_item" v-for="(item,index) in imgArr" :key="index">
                        <view class="select_block" v-if="moreSelectState">
                            <label class="itemCheckbox">
                              <checkbox :color="defaultColor" :value="publicFun.toStringFun(item)"></checkbox>
                            </label>
                        </view>
                        <image @tap="lookBigImage(item.contentArr)" class="material_library_detail_item_img" mode="aspectFit" :src="item.contentArr[0]+'?x-oss-process=style/preview'"></image>
                        <view class="down_load_btn" @click.stop="downLoadItemFun(item,'image')">下载<text v-if="item.contentArr.length>1">【{{item.contentArr.length}}张】</text></text></view>
                    </view>
                </checkbox-group>
                <view @change="checkboxChange" class="material_library_detail_two" v-if="showType=='imgArr'">
                    <view class="material_library_detail_type_title">【{{typeName}}】</view>
                    <scroll-view scroll-y @scrolltolower="onReachBottom2" class="leftScrollType">
                        <view class="material_library_detail_left" @tap="selectProItemFun(item,index)" v-for="(item,index) in imgArr" :key="index">
                            <view class="">{{item.name}}</view>
                            <view class="active" v-if="curProIndex==index" :style="'background: '+defaultColor"></view>
                        </view>
                    </scroll-view>
                    <view scroll-y class="RightProductContainer">
                        <view class="material_library_detail_item_three" v-for="(item,index) in curProData.contentArr" :key="index">
                            <image @tap="lookBigImage(curProData.contentArr,index)" class="material_library_detail_item_img" mode="aspectFit" :src="item+'?x-oss-process=style/preview'"></image>
                            <view class="down_load_btn" @click.stop="downLoadItemFun({contentArr:[item]},'image')">下载</view>
                        </view>
                    </view>
                </view>
                <!-- </view> -->
                <checkbox-group class="material_library_detail" @change="checkboxChange" v-if="showType=='video'">
                    <view class="material_library_detail_two_item" v-for="(item,index) in videoList" :key="index">
                        <view class="select_block" v-if="moreSelectState">
                            <label class="itemCheckbox">
                              <checkbox :color="defaultColor" :value="publicFun.toStringFun(item)"></checkbox>
                            </label>
                        </view>
                        <view class="material_library_detail_two_item_block">
                            <image class="material_library_detail_two_item_bg" src="https://image1.sansancloud.com/linwenlaoshi/2020_9/10/17/51/3_524.jpg"></image>
                            <image @click.stop="filePreviewFun(item,index)" class="material_library_detail_two_item_play" src="https://image1.sansancloud.com/linwenlaoshi/2020_9/10/18/4/54_5.jpg"></image>
                            <view class="video_blcok" @click.stop="filePreviewFun(item,index)">
                                <image style="width: 100%;height: 100%;background: #fff;" mode="aspectFit" :src="item.headimg&&item.headimg!='undefined'?item.headimg:'https://image1.sansancloud.com/linwenlaoshi/2020_9/21/14/39/30_733.jpg?x-oss-process=style/preview_120'"></image>
                                <!-- <video-component id="video" :receiveData="item"></video-component> -->
                            </view>
                            <image class="material_library_detail_item_img" mode="aspectFit" src="https://image1.sansancloud.com/linwenlaoshi/2020_9/10/17/12/37_505.jpg?x-oss-process=style/preview_120"></image>
                            <view class="down_load_btn" style="left: 50rpx" @click.stop="downLoadItemFun(item,'video')">下载</view>
                        </view>
                        <text class="material_library_detail_two_item_name">{{item.name}}</text>
                    </view>
                </checkbox-group>
            </view>
            <view class="noproduct" v-if="(selectTabIndex!='2'&&imgArr.length==0)||(selectTabIndex=='2'&&videoList.length==0)">
              <image mode="widthFix" src='https://image1.sansancloud.com/xianhua/2019_12/16/15/54/55_950.jpg?x-oss-process=style/preview_120'></image>
              <text>没有相关素材</text>
            </view>
            
        </view>
       <view class="bottom_btn_blcok" v-if="selectTabIndex!=1">
           <view class="bottom_btn_item_left">
               <view class="bottom_btn_item" style="border: 1rpx solid #ddd;" @click="moreSelectFun()" v-if="!moreSelectState">
                   <text>多选</text>
               </view>
               <view class="bottom_btn_item" style="border: 1rpx solid #ddd;" @click="selectedDownLoadFun()" v-if="moreSelectState">
                   <text>选中下载</text>
               </view>
               <view class="bottom_btn_item" style="border: 1rpx solid #ddd;margin-left: 20rpx;" @click="cancelMoreSelectFun()" v-if="moreSelectState">
                   <text>取消多选</text>
               </view>
           </view>
           <view class="bottom_btn_item" :style="'color:#fff;background: '+defaultColor" @click="downLoadAllFun()">
               <text>全部下载</text>
           </view>
       </view>
       <view class="bottom_btn_blcok" v-else>
           <view class="bottom_btn_item_left"></view>
           <view class="bottom_btn_item" :style="'color:#fff;background: '+defaultColor" @click.stop="downLoadItemFun(curProData,'image')">
               <text>全部下载</text>
           </view>
       </view>
       <!-- 视频预览 -->
       <view class="file_preview_block" v-if="filePreviewData">
           <view class="file_preview_bg" @tap="closeFilePreviewFun"></view>
           <view class="file_preview_ban">
               <video-component id="file_video" v-if="filePreviewData.fileType=='video'" :receiveData="filePreviewData"></video-component><!-- 视频-->
               <!-- <component-audio id="audio" v-if="filePreviewData.fileType=='audio'" :receiveData="filePreviewData"></component-audio> -->
           </view>
           <view class="down_load_btn_block">
               <text class="down_load_btn_text" :style="'background: '+defaultColor" @click.stop="downLoadItemFun(filePreviewData,'video')">下载视频</text>
           </view>
       </view>
    </view>
</template>

<script>
import publicFun from '../../wxcomponents/public/publicFun.wxs'

export default {
  data() {
    return {
      materialLibraryDetail:null,
      materialLibraryDetailTypeList:[
          {name:'海报',index:0},
          {name:'组图',index:1},
          {name:'视频',index:2},
      ],
      materialLibraryDetailTypeIndex:0,
      selectTabIndex: 0,
      typeName:'',
      showType:'',
      params: {},
      listPage: {
        page: 1,
        pageSize: 20,
        totalSize: 0,
        tagName:'海报',
      },
      downLoadNum:0,
      setting: "",
      secondColor:'',
      defaultColor:'',
      moreSelectState:false,
      checkedItemList:[],
      statusBarHeightOne:getApp().globalData.statusBarHeightOne,
      screenHeight:getApp().globalData.screenHeight,
      imgArr:[],
      videoArr:['https://image1.sansancloud.com/xianhua/2020_9/3/18/57/52_906_视频1.mp4'],
      videoList:[],
      filePreviewData:null,
      curProData:null,
      curProIndex:0,
    };
  },
  props: {},
  onLoad: function (options) {
    this.publicFun = publicFun;
    let that = this;
    that.initSetting();
    console.log('===options===', options,that.screenHeight);
    if(options.typeName){
        that.typeName=options.typeName
    }
    if(options.type){
        let index=(options.type==0?0:2)
        that.selectTabIndex=index;
        that.materialLibraryDetailTypeIndex=index;
        that.listPage.tagName=that.materialLibraryDetailTypeList[index].name
    }
    that.listPage=Object.assign({},that.listPage,options)
    that.getMaterialLibraryDetail(that.listPage); 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.reflesh == 1) {
      this.onPullDownRefresh();
    }
	this.setData({
        setting:getApp().globalData.setting,
        defaultColor:getApp().globalData.setting.platformSetting.defaultColor,
        secondColor:getApp().globalData.setting.platformSetting.secondColor,
       })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this;
    that.listPage.page=1
    that.getMaterialLibraryDetail(that.listPage);
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('===onReachBottom====');
    let that = this;
    if(that.selectTabIndex==1){
        return
    }
    if (that.listPage.totalSize > that.listPage.page * that.listPage.pageSize) {
      that.listPage.page++
      that.getMaterialLibraryDetail(that.listPage);
    }else{
        wx.showToast({
          title: "到底了~",
          image: '/wxcomponents/images/icons/tip.png',
          duration: 1000
        });
    }
  },
  onShareTimeline:function(){
    return this.shareFun();
  },
  onShareAppMessage: function (res) {
    console.log(res);
    return this.shareFun();
  },
  methods: {
    onReachBottom2:function(){
        console.log('===onReachBottom====');
        let that = this;
        if (that.listPage.totalSize > that.listPage.page * that.listPage.pageSize) {
          that.listPage.page++
          that.getMaterialLibraryDetail(that.listPage);
        }else{
            wx.showToast({
              title: "到底了~",
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
        }
    },
    selectProItemFun:function(item,index){
       let that=this;
       that.curProData=item;
       that.curProIndex=index
    },
    closeFilePreviewFun:function(){
        let that=this;
        console.log("=====onUnload=====");
        if(that.filePreviewData.fileType=='audio'){
            try{
                that.selectComponent("#audio").stopAudioFun();
            }catch(e){
                //TODO handle the exception
            }
        }else{
            try{
                that.selectComponent("#file_video").onStopPlay()
            }catch(e){
                //TODO handle the exception
            }
        }
        that.filePreviewData=null
    },
    filePreviewFun:function(itemData,index){
        let that=this;
        console.log("===filePreviewFun===",itemData);
        let filePreviewData= Object.assign({},itemData,{fileType:itemData.fileType})
        if(itemData.fileType=='video'){
            filePreviewData.type='video_other';
        }
        console.log("filePreviewData",filePreviewData)
        that.filePreviewData=filePreviewData
    },
    backPerPageFun:function(){
        wx.navigateBack()
    },
    selectedDownLoadFun:function(){
        let that=this;
        for(let i=0;i<that.checkedItemList.length;i++){
            that.checkedItemList[i]=JSON.parse(that.checkedItemList[i])
        }
        that.downLoadAllFun(that.checkedItemList)
    },
    moreSelectFun:function(){
        let that=this;
        that.moreSelectState=true
    },
    cancelMoreSelectFun:function(){
        let that=this;
        that.moreSelectState=false
    },
    checkboxChange: function (e) {
        let that=this;
        console.log('--------checkBox------');
        console.log(e.detail.value, 'value+++');
        that.checkedItemList=e.detail.value
    },
    downLoadAllFun:function(fileList){
        console.log("===fileList===",fileList)
        let that=this;
        let type='';
        let lengthStr=0;
        let count=0;
        let allFileData=[];
        if(fileList&&fileList.length==0){
            wx.showToast({
              title: "请选择素材！",
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
            return
        }
        if(that.selectTabIndex==2){
            type='video';
            let videoList=fileList||that.videoList
            for(let i=0;i<videoList.length;i++){
                allFileData.push(videoList[i].content)
            }
            lengthStr=videoList.length
        }else{
            let imgArr=fileList||that.imgArr
            if(imgArr.length!=0){
                for(let j=0;j<imgArr.length;j++){
                    allFileData=allFileData.concat(imgArr[j].contentArr)
                    lengthStr+=imgArr[j].contentArr.length
                }
            }
        }
        console.log("======allFileData====",allFileData)
        that.shareFormItemFun(allFileData,type,function(res){
            count++;
            console.log("====count====",count,res)
            if(count==lengthStr){
                wx.hideLoading();
                wx.showToast({
                  title: '素材已下载至手机相册',
                  icon: 'none',
                  duration: 2000
                })
            }else{
                wx.showLoading({
                    title: '素材已下载'+count+'/'+lengthStr,
                })
            }
        })
    },
    lookBigImage:function(itemData,index){
        console.log("====lookBigImage====",itemData);
        getApp().globalData.lookBigImage(itemData,index||0)
    },
    downLoadItemFun:function(listData,type){
        let that=this;
        let lengthStr=0;
        let count=0;
        if(type=='image'){
            lengthStr=listData.contentArr.length;
        }else{
            lengthStr=1
        }
        that.shareFormItemFun(listData,type,function(res){
            count++;
            console.log("====count====",count,res)
            if(count==lengthStr){
                wx.hideLoading();
                wx.showToast({
                  title: '素材已下载至手机相册',
                  icon: 'none',
                  duration: 2000
                })
            }else{
                wx.showLoading({
                    title: '素材已下载'+count+'/'+lengthStr,
                })
            }
        })
    },
    // 朋友圈样式方法
    shareFormItemFun:function(data,type,callback){
        let that=this;
        let fileList=data.contentArr||data;
        let value=data.description||'';
        console.log("shareFormItemFun",data,fileList);
        // if(value){
        //     wx.setClipboardData({
        //       data: value,
        //       success: function (res) {
        //         wx.getClipboardData({
        //           success: function (res) {
        //             wx.showToast({
        //               title: '文案已复制',
        //               icon: 'none',
        //               duration: 1000
        //             });
        //           }
        //         });
        //       }
        //     });
        // }
        wx.authorize({
         scope: 'scope.writePhotosAlbum',
         success:function(e){
            console.log("success",e)
            setTimeout(function(){
                wx.showLoading({
                    title: '素材下载中..',
                })
                if(fileList&&fileList.length!=0){
                    let conut = 0;
                    for (let i = 0; i < fileList.length;i++){
                      that.downloadFileFun(fileList[i],type,callback)
                    }
                }
            },1000)
         },
         fail:function(e){
            console.log("fail",e)
         },
        })
    },
    downloadFileFun: function(url,type,callback){
        let that=this;　　　　　　　　　　　　　　　//触发函数
        console.log(url,type)
        if(url){
            url=url.replace('http://','https://');
        }
        wx.downloadFile({
          url: url,　　　　　　　//需要下载的图片url
          success: function (res) {　　　　　　　　　　　　//成功后的回调函数
            if(!type||type=='img'||type=='image'){
                that.saveImageToPhotosAlbumFun(res,callback)
            }else if(type||type=='video'){
                that.saveVideoToPhotosAlbumFun(res,callback)
            }
          },
          fail:function(res){
            wx.hideLoading();
            wx.showToast({
              title: '素材下载失败！',
              icon: 'none',
              duration: 2000
            })
          }
        });
    },
    saveImageToPhotosAlbumFun:function(res,callback){
        wx.saveImageToPhotosAlbum({　　　　　　　　　//保存到本地
          filePath: res.tempFilePath,
          success(res) {
              console.log("====saveImageToPhotosAlbumFun===",res)
              if(callback){
                  callback(res)
              }
          },
          fail: function (err) {
            wx.hideLoading();
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                  }
                }
              })
            }
          }
        })
    },
    saveVideoToPhotosAlbumFun:function(res,callback){
        wx.saveVideoToPhotosAlbum({　　　　　　　　　//保存到本地
          filePath: res.tempFilePath,
          success(res) {
            if(callback){
                callback(res)
            }
          },
          fail: function (err) {
            wx.hideLoading();
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                  }
                }
              })
            }
          }
        })
    },
    bindTypeItem:function(index,type){
        let that=this;
        console.log("==bindTypeItem==",index,type)
        that.listPage.page=1
        that.checkedItemList=[];
        that.moreSelectState=false
        that.selectTabIndex=index;
        that.showType='';
        that.listPage.tagName=that.materialLibraryDetailTypeList[index].name
        that.getMaterialLibraryDetail(that.listPage); 
        // that.listPage.categoryId=that.productTypeList[index].id;
        // that.getData(that.listPage,'upload');
    },
    shareFun:function(){
        let that = this;
        that.closeZhezhao();
        let customFormData = that.selectComponent("#formCommitList").data.customFormData;
        console.log('that.data.customFormData:', customFormData);
        let params = {
          customFormId: customFormData.id
        };
        let shareName = customFormData.name;
        console.log('params:', params);
        return getApp().globalData.shareForFx2('form_commit_list', shareName, params, '', 'customFormId');
    },
    /* 组件事件集合 */
    tolinkUrl: function (data) {
      let linkUrl = data.currentTarget ? data.currentTarget.dataset.link : data;
      console.log("==linkUrl===", linkUrl);
      getApp().globalData.linkEvent(linkUrl);
    },
    getMaterialLibraryDetail: function (params) {
      let that = this;
      // that.showType=''
      let materialLibraryDetailData = getApp().globalData.AddClientUrl("/wx_find_album_materials.html", params, 'get');
      console.log('==materialLibraryDetailData===', materialLibraryDetailData);
      wx.request({
        url: materialLibraryDetailData.url,
        data: materialLibraryDetailData.params,
        header: getApp().globalData.headerPost,
        method: 'get',
        success: function (res) {
          console.log(res);
          let data = res.data.relateObj.result;
          that.listPage.pageSize = res.data.relateObj.pageSize;
          that.listPage.curPage = res.data.relateObj.curPage;
          that.listPage.totalSize = res.data.relateObj.totalSize;
          if (res.data.errcode == 0) {
              for(let i=0;i<data.length;i++){
                  if(data[i].content){
                      data[i].contentArr=data[i].content.split(',');
                  }
                  let url=data[i].content.replace(" ","%20")
                  if(data[i].type=='1'){
                      data[i].fileType='video'
                      data[i].jsonData={
                          source:url,
                          autoPlay:0,
                          type:'video_other',
                          id:'fileVideoComponent_'+data[i].id,
                          height:'400px',
                          width:'750rpx',
                          poster:'',
                      }
                  }else{
                      data[i].fileType='img'
                  }
              }
              console.log("dataList",data)
            if(data.length!=0){
                if(params.tagName=='视频'){
                    that.showType='video'
                    let videoList=that.videoList
                    if(params.page==1){
                        videoList=[]
                    }
                    that.videoList=videoList.concat(data);
                    console.log("==that.videoList==",that.videoList)
                }else{
                    if(that.selectTabIndex==0){
                        that.showType='img'
                    }else if(that.selectTabIndex==1){
                        that.showType='imgArr';
                    }
                    let imgArr=that.imgArr
                    if(params.page==1){
                        imgArr=[];
                    }
                    that.imgArr=imgArr.concat(data)
                    if(that.selectTabIndex==1&&that.imgArr.length!=0){
                        that.curProData=that.imgArr[0]
                    }
                    console.log("==that.imgArr==",that.imgArr)
                }
            }
          } 
        }
      });
    },
    closeZhezhao: function () {
      let that = this;
      let selectTab = that.selectTab;
      that.setData({
        showCount: false
      });
      that.setData({
        selectTabIndex: -1
      });

      for (let i = 0; i < selectTab.length; i++) {
        selectTab[i].state = false;
      }

      that.setData({
        selectTab: selectTab
      });
    },

    initSetting() {
      this.setData({
        setting: getApp().globalData.setting
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style scoped>
@import "./index.css";
</style>